package com.blog.dazi.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ChatService {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    public int save(String mess) {

        JSONObject jsonObject = JSON.parseObject(mess);
        String senderTel = (String) jsonObject.get("senderTel");
        String receiverTel = (String) jsonObject.get("receiverTel");
        String message = (String) jsonObject.get("message");
        //不能自己给自己发消息
        if(senderTel.equals(receiverTel)){
            return 0;
        }
        String sql = "insert into sys_chat (sender_tel,receiver_tel,message) values (?,?,?)";
        return jdbcTemplate.update(sql,senderTel,receiverTel,message);

    }

    public List<Map<String, Object>> findBySenderAndReceiver(String senderTel, String receiverTel) {

        String sql = "select * from ( " +
                "select *,'to' direction  from sys_chat where sender_tel = ? and receiver_tel = ? " +
                "UNION  " +
                "select *,'back' direction  from sys_chat where sender_tel = ? and receiver_tel = ?) a ORDER BY a.create_time";

        return jdbcTemplate.queryForList(sql,senderTel,receiverTel,receiverTel,senderTel);
    }

    public List<Map<String, Object>> userList(String tel) {

        String sql = "select a.id userId,a.dazi_number daziNumber,a.username, b.photo userPhoto from sys_user a,sys_user_photo b where a.photo_id = b.id and a.phone_number in ( select DISTINCT sender_tel from sys_chat where receiver_tel = ? order by create_time desc)";
        return jdbcTemplate.queryForList(sql,tel);
    }

    public boolean get(String type,String tel) {

        String sql = "select id from sys_chat where is_read = 0 and receiver_tel = ?";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql,tel);
        if(maps.size()>0){
            return true;
        }

        return false;
    }
}
